package com.sskj.level.ui.fragment;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.widget.RxRadioGroup;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.common.base.App;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.depthlib.data.DepthData;
import com.sskj.depthlib.view.DepthMapView;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.AssetDetailBean;
import com.sskj.level.bean.AssetListBean;
import com.sskj.level.bean.BuySellEnum;
import com.sskj.level.bean.CoinType;
import com.sskj.level.bean.CoinUpdateBean;
import com.sskj.level.bean.HuilvContentBean;
import com.sskj.level.bean.TradeSetBean;
import com.sskj.level.bean.UserInfo;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.BuyAndSellFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.Constants;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.CoinDotBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.PopUtil;
import com.sskj.lib.util.TipUtil;
import com.sskj.lib.widget.SpinnerPop;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.LEVEL_FRAGMENT_BUY_AND_SELL)//合约交易买卖
public class BuyAndSellFragment extends BaseFragment<BuyAndSellFragmentPresenter> {
    @BindView(R2.id.rbBuy)
    RadioButton rbBuy;
    @BindView(R2.id.rbSell)
    RadioButton rbSell;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R2.id.llPriceMode)
    LinearLayout llPriceMode;
    @BindView(R2.id.llLevelMode)
    LinearLayout llLevelMode;
    @BindView(R2.id.etPrice)
    EditText etPrice;
    @BindView(R2.id.tvDecrease)
    TextView tvDecrease;
    @BindView(R2.id.cuttingLine)
    TextView cuttingLine;
    @BindView(R2.id.tvIncrease)
    TextView tvIncrease;
    @BindView(R2.id.llAddAndDe)
    LinearLayout llAddAndDe;
    @BindView(R2.id.rlEditPrice)
    RelativeLayout rlEditPrice;
    @BindView(R2.id.llHidePrice)
    RelativeLayout llHidePrice;
    @BindView(R2.id.etNum)
    EditText etNum;

    @BindView(R2.id.tvMoney)
    TextView tvMoney;
    @BindView(R2.id.tvNumRight)
    TextView tvNumRight;


    @BindView(R2.id.tvTradeMoney)
    TextView tvTradeMoney;
    @BindView(R2.id.tvBoomRate)
    TextView tvBoomRate;
    @BindView(R2.id.etStopWinDot)
    EditText etStopWinDot;

    @BindView(R2.id.etStopLoseDot)
    EditText etStopLoseDot;
    @BindView(R2.id.btTrade)
    Button btTrade;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.tvMarketLimit)
    TextView tvMarketLimit;

    @BindView(R2.id.frameLayoutFive)
    FrameLayout frameLayoutFive;
    @BindView(R2.id.tvLevel)
    TextView tvLevel;
    @BindView(R2.id.tv_prefer_rate)
    TextView tvPreferRate;
    @BindView(R2.id.llBoomRate)
    RelativeLayout llBoomRate;

    @BindView(R2.id.depthMapView)
    DepthMapView depthMapView;
    @BindView(R2.id.huilvLayout)
    LinearLayout huilvLayout;
    @Inject
    UserViewModel userViewModel;
    DecimalFormat mFormat = new DecimalFormat("0.0000");
    int[] pagers = new int[]{
            25, 50, 75, 100
    };

    @BindView(R2.id.cb25)
    View cb25;
    @BindView(R2.id.v_divide_25)
    View vDivide25;
    @BindView(R2.id.cb50)
    View cb50;
    @BindView(R2.id.v_divide_50)
    View vDivide50;
    @BindView(R2.id.cb75)
    View cb75;
    @BindView(R2.id.v_divide_75)
    View vDivide75;
    @BindView(R2.id.cb100)
    View cb100;

    private int pager = 0;
    @Autowired
    String code = "USDT";//币种类型code
    String codeRight = "USDT";//币种类型code
    String type = "BTC";//币种类型


    private BottomSheetDialog priceModeSheet;
    private boolean isBuy = true;
    private boolean isMarketPrice = true;  // 市价限价  （默认限价）
    private String marketPrice = "5000";//市价
    private String currentPrice = "5000";//限价
    private String usdtMoney = "1000";//可用USDT
    private String rate = "0.0001";//加减的点
    private String rateNum = "0.01";// 数量加减的点
    private int priceKeepDot = 4;//价格小数点位
    private int numUSTDKeepDot = 4;//数量小数点位
    private int numCoinKeepDot = 4;//数量小数点位
    private String maxTradeCoin = "10";//最大可交易币种数量
    private String minTradeCoin = "10";//最小可交易币种数量
    private String fee = "0.15";//手续费
    private Double level = 1d;//杠杆
    private String minFloatPrice = "0";//最小浮动价
    private String dotDistance = "0";//点差
    private String levels;//杠杆
    private UserData userData;
    private String minLoss = "0";//最小止损
    private String maxLoss = "0";//最大止损
    private String maxWin = "0";//最大止赢
    private String minWin = "0";//最小止赢
    private String distancePrice = "0";
    private int dotLoss;
    private int dotWin;
    private String winMinPrice;
    private String winMaxPrice;
    private String lossMinPrice;
    private String lossMaxPrice;
    private String stopLossPrice = "--";
    private String stopWinPrice = "--";
    private String orderPrice;
    private Disposable subscribe;
    private String cnyPrice;
    private SpinnerPop marketLimitPop;
    private SpinnerPop levelPop;
    private MaterialDialog boomDialog;
    //惠率和下单的dialog
    private MaterialDialog huiLvDialog;
    private String paperValue = "1";
    private String transWare = "";
    //惠率弹窗内容
    private String huilvContent = "";
    //是否选择过仓位，杠杆改变时使用
    private boolean isSetPositions = false;
    private boolean clearCheck = false;
    private int red;
    private GradientDrawable backgroundred;
    private GradientDrawable backgrounrdgreen;
    private int green;
    private GradientDrawable backgroundgray;
    private int gray;


    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_buy_sell;
    }

    @Override
    public BuyAndSellFragmentPresenter getPresenter() {
        return new BuyAndSellFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @SuppressLint("InvalidR2Usage")
    @Override
    public void initView() {


        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        ARouter.getInstance().inject(this);
        if (code.contains("_") || code.contains("/")) {
            type = code.replace("_", "/").split("/")[0].toUpperCase();
            codeRight = code.replace("_", "/").split("/")[1].toUpperCase();
        }
        etPrice.setSaveEnabled(false);
        depthMapView.setDrawText(true);
        depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
        depthMapView.setShader(true, color(R.color.lib_depth_buy_top), color(R.color.lib_depth_buy_middle), color(R.color.lib_depth_buy_bottom), 1000);
        depthMapView.setShader(false, color(R.color.lib_depth_sell_top), color(R.color.lib_depth_sell_middle), color(R.color.lib_depth_sell_bottom), 1000);
        initClick();
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
//                usdtMoney = userData.getWallone();
                mPresenter.getUSDT(code);
            } else {
                userData = null;
                usdtMoney = "0";
                btTrade.setText(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment23));
            }
            updateUI();
        });
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayoutFive, (Fragment) ARouter.getInstance()
                        .build(RConfig.LEVEL_FRAGMENT_FIVE)
                        .withString(Constans.CODE, code)
                        .navigation()
                ).commitAllowingStateLoss();
    }

    @Override
    public void initData() {
        mPresenter.getCoinInfo(code);
        mPresenter.getDepthData(code);
        //惠率弹窗
        //惠率
        if (!TextUtils.isEmpty(SPUtil.get(Constants.SP_ACCOUNT, ""))) {
            mPresenter.getHuiLv();
            mPresenter.request();
            userViewModel.update();
        }
//        startTimer();

    }

    /**
     * 更换币种
     *
     * @param coinType
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CoinType coinType) {
        isBuy = coinType.isBuy();
        isMarketPrice = true;
        code = coinType.getCode();
        codeRight = coinType.getCode().split("_")[1].toUpperCase();
        type = coinType.getCode().split("_")[0].toUpperCase();

        Integer dot = CoinDotBean.getDot(code);
        rate = dot == 2 ? "0.01" : dot == 4 ? "0.0001" : "0.00001";
        priceKeepDot = dot;
        refresh();
        //变换深度图的限制
        depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
    }

    /**
     * 刷新页面
     */
    @Subscribe(code = RxBusCode.LEVEL_FRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        mPresenter.getCoinInfo(code);
        mPresenter.getDepthData(code);
        //惠率弹窗

        //惠率
        if (!TextUtils.isEmpty(SPUtil.get(Constants.SP_ACCOUNT, ""))) {
            mPresenter.getHuiLv();
            mPresenter.request();
            userViewModel.update();
        }

        //刷新时，恢复一些默认属性
        isMarketPrice = true;
        isBuy = true;
        initRadioGroup();
        //张数清零
        etNum.setText("");
        etNum.clearFocus();
        //仓位置false
        isSetPositions = false;
    }


    /**
     * 市价更新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(CoinBean stock) {
        if (stock.getCode().equals(code) && getActivity() != null) {
            marketPrice = stock.getPrice();
            if (isMarketPrice) {
                etPrice.setText(marketPrice);
            }
//            leftCoinMoney.setText(stock.getCnyPrice());
            changeShowData();
        }
    }

    public void updateCoinData(CoinUpdateBean coinUpdateBean) {
        transWare = coinUpdateBean.getTrans_ware();
        currentPrice = marketPrice = coinUpdateBean.getPrice();
        type = code.replace("_", "/").split("/")[0].toUpperCase();
        fee = new BigDecimal(coinUpdateBean.getShouPer()).multiply(new BigDecimal("0.01")).toPlainString();
        minFloatPrice = coinUpdateBean.getSlidingScalePrice();
        dotDistance = coinUpdateBean.getSpread();
        distancePrice = new BigDecimal(minFloatPrice).multiply(new BigDecimal(dotDistance)).toPlainString();
        minLoss = coinUpdateBean.getMinStopLoss();
        maxLoss = coinUpdateBean.getStopLoss();
        minWin = coinUpdateBean.getMinStopProfit();
        maxWin = coinUpdateBean.getStopProfit();
        minTradeCoin = coinUpdateBean.getMinDealNum();
        levels = coinUpdateBean.getLevels();
        if (coinUpdateBean.getLevels().length() > 0) {
            level = Double.valueOf(coinUpdateBean.getLevels().split(",")[0]);
        }
        paperValue = coinUpdateBean.getPaperValue();
        updateLevelButton();
        updateUI();

    }

    /**
     * 动态更新杠杆按钮
     */
    private void updateLevelButton() {
        levelPop = PopUtil.popSpinner(getContext(), (recyclerView, position, v) -> {
            levelPop.dismiss();
            etNum.clearFocus();
            level = Double.valueOf(levels.split(",")[position]);
            calculateNumByLecver();
            updateUI();
        }, levels.split(","));

    }


    @SuppressLint("InvalidR2Usage")
    private void initClick() {
        RxRadioGroup.checkedChanges(radioGroup)
                .subscribe(clickId -> {
                    if (!isBuy && clickId == rbBuy.getId()) {//购买
                        isBuy = true;
//                        isMarketPrice = true;
                        updateUI();
                    } else if (isBuy && clickId == rbSell.getId()) {//出售
                        isBuy = false;
//                        isMarketPrice = true;
                        updateUI();
                    }
                });
        //爆仓的dialog
        ClickUtil.click(tvBoomRate, () -> {
            mPresenter.getLevelAndTrade(code);
        });
        //惠率的dialog
        ClickUtil.click(huilvLayout, () -> {
            if (TextUtils.isEmpty(huilvContent)) {
                return;
            }
            huiLvDialog = TipUtil.getHuiLvTip(getActivity(), getResources().getString(R.string.level_shouxujvhui), huilvContent, () -> {
                huiLvDialog.dismiss();
            });
            huiLvDialog.show();
        });
        //杠杆

        red = Color.parseColor("#F23937");
        backgroundred = new GradientDrawable();
        backgroundred.setShape(GradientDrawable.OVAL);
        backgroundred.setCornerRadius(20);
        backgroundred.setColor(red);

        green = Color.parseColor("#10B478");
        backgrounrdgreen = new GradientDrawable();
        backgrounrdgreen.setShape(GradientDrawable.OVAL);
        backgrounrdgreen.setCornerRadius(20);
        backgrounrdgreen.setColor(green);

        gray = Color.parseColor("#878D9D");
        backgroundgray = new GradientDrawable();
        backgroundgray.setShape(GradientDrawable.OVAL);
        backgroundgray.setCornerRadius(20);
        backgroundgray.setColor(gray);

        initRadioGroup();

        ClickUtil.click(cb25, () -> {
            if (clearCheck) {
                clearCheck = false;
                return;
            }
            initRadioGroup();
            if (TextUtils.isEmpty(maxTradeCoin)) {
                etNum.setText("0");
                return;
            }
            cb25.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            pager = pagers[0];
            initInput(pager);
        });

        ClickUtil.click(cb50, () -> {
            if (clearCheck) {
                clearCheck = false;
                return;
            }
            initRadioGroup();
            if (TextUtils.isEmpty(maxTradeCoin)) {
                etNum.setText("0");
                return;
            }
            cb25.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            vDivide25.setBackgroundColor(isBuy ? green : red);
            cb50.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            pager = pagers[1];
            initInput(pager);

        });
        ClickUtil.click(cb75, () -> {
            if (clearCheck) {
                clearCheck = false;
                return;
            }
            initRadioGroup();
            if (TextUtils.isEmpty(maxTradeCoin)) {
                etNum.setText("0");
                return;
            }
            cb25.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            vDivide25.setBackgroundColor(isBuy ? green : red);
            cb50.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            vDivide50.setBackgroundColor(isBuy ? green : red);
            cb75.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            pager = pagers[2];
            initInput(pager);

        });
        ClickUtil.click(cb100, () -> {
            if (clearCheck) {
                clearCheck = false;
                return;
            }
            initRadioGroup();
            if (TextUtils.isEmpty(maxTradeCoin)) {
                etNum.setText("0");
                return;
            }
            cb25.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            vDivide25.setBackgroundColor(isBuy ? green : red);
            cb50.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            vDivide50.setBackgroundColor(isBuy ? green : red);
            cb75.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            vDivide75.setBackgroundColor(isBuy ? green : red);
            cb100.setBackground(isBuy ? backgrounrdgreen : backgroundred);
            pager = pagers[3];
            initInput(pager);
        });

        ClickUtil.click(llPriceMode, () -> {
            if (marketLimitPop == null) {
                marketLimitPop = PopUtil.popSpinner(getActivity(), (recyclerView, position, v) -> {

                    marketLimitPop.dismiss();
                    if (position == 0 && !isMarketPrice) {
                        isMarketPrice = true;
                        updateUI();
                        tvNumRight.setText(codeRight);
                    } else if (position == 1 && isMarketPrice) {
                        isMarketPrice = false;
                        updateUI();
                        tvNumRight.setText(type);
                    }
                    if (!isBuy) {
                        tvNumRight.setText(type);
                    }

                }, App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment35), App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment36));
            }
            marketLimitPop.showPopupWindow(tvMarketLimit);
        });
        ClickUtil.click(llLevelMode, () -> {
            if (levelPop == null)
                return;

            levelPop.showPopupWindow(tvLevel);
        });
        ClickUtil.click(100, tvDecrease, () -> {
            if (isMarketPrice) {
                return;
            }
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            String decrease = "-" + rate;
            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(decrease));
            if (priceDecimal.doubleValue() <= 0) {
                etPrice.setText("0");
            } else {
                etPrice.setText(NumberUtil.keep(priceDecimal.toString(), priceKeepDot));
            }
        });
        ClickUtil.click(100, tvIncrease, () -> {
            if (isMarketPrice) {
                return;
            }
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            String increase = rate;
            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(increase));
            etPrice.setText(NumberUtil.keep(priceDecimal.toString(), priceKeepDot));
        });
        RxTextView.afterTextChangeEvents(etPrice)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable().toString())) {
                        currentPrice = "0";
                    } else {
                        currentPrice = value.editable().toString();
                    }
                    calculateMaxTrade();
                    changeShowData();
                }, e -> System.out.println(e));
        RxTextView.afterTextChangeEvents(etNum)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable()) || Double.valueOf(value.editable().toString()) == 0 ||
                            TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                    } else {
                        if (Double.valueOf(value.editable().toString()) > Double.valueOf(maxTradeCoin)) {
                            etNum.setText(maxTradeCoin);
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment42));
                        }

                    }
                    if (etNum.isFocused() && isSetPositions) {
                        clearCheck = true;
                        initRadioGroup();
                        isSetPositions = false;
                    }
                    changeShowData();
                });
    }

    void initInput(int pager) {

        String s = String.format("%.4f", new BigDecimal(maxTradeCoin).multiply(new BigDecimal(pager)).multiply(new BigDecimal(0.01)).doubleValue());
        //仓位选择
        isSetPositions = true;
        etNum.clearFocus();
        etNum.setText(s);
        etNum.setSelection(s.length());
    }


    void initRadioGroup() {
        //初始化，全部置灰
        cb25.setBackground(backgroundgray);
        vDivide25.setBackgroundColor(gray);
        cb50.setBackground(backgroundgray);
        vDivide50.setBackgroundColor(gray);
        cb75.setBackground(backgroundgray);
        vDivide75.setBackgroundColor(gray);
        cb100.setBackground(backgroundgray);
    }


    /**
     * 更新杠杆和IM COIN
     */
    public void updateLevelAndTrade(TradeSetBean bean) {
        if (bean != null) {
            levels = bean.getLeverage();
            if (bean.getLeverage().length() > 0) {
                level = Double.valueOf(bean.getLeverage().split(",")[0]);
            }
            String transWare = bean.getTrans_ware();
            if (TextUtils.isEmpty(transWare)) {
                return;
            }
            boomDialog = TipUtil.getSureTip(getActivity(), String.format(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment32), transWare), () -> {
                boomDialog.dismiss();
            });
            boomDialog.show();
        }
    }

    /**
     * 更新界面根据
     * 买入卖出，市价限价，币种，可用金额 变化 初始化界面
     */
    @SuppressLint("InvalidR2Usage")
    private void updateUI() {
//        Log.e("TAG updateUI", "code: " + code);
        Integer dot = CoinDotBean.getDot(code);
        rate = dot == 2 ? "0.01" : dot == 4 ? "0.0001" : "0.00001";
        priceKeepDot = dot;
//        Log.e("TAG updateUI", "code: " + code +" priceKeepDot: " + priceKeepDot + " marketPrice: " +marketPrice);
        calculateMaxTrade();
        if (radioGroup == null)
            return;
        updateUSDT();
        radioGroup.check(isBuy ? R.id.rbBuy : R.id.rbSell);
        rbBuy.setTextColor(getResources().getColor(isBuy ? R.color.white : R.color.black));
        rbSell.setTextColor(getResources().getColor(isBuy ? R.color.black : R.color.white));
        tvMarketLimit.setText(isMarketPrice ? App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment35) : App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment36));
        tvNumRight.setText((isBuy && isMarketPrice) ? codeRight : type);
        //  rlEditPrice.setVisibility(isMarketPrice ? View.GONE : View.VISIBLE);
        //  llHidePrice.setVisibility(isMarketPrice ? View.VISIBLE : View.GONE);
        etPrice.setText(marketPrice);
        tvPrice.setText(marketPrice);
        tvLevel.setText(level.intValue() + "");
        RxTextView.afterTextChangeEvents(etPrice)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable().toString())) {
                        currentPrice = "0";
                    } else {
                        currentPrice = value.editable().toString();
                    }
                    calculateMaxTrade();
                    changeShowData();
                }, e -> System.out.println(e));
//        etNum.setText("");
//        etStopLoseDot.setText("");
//        etStopWinDot.setText("");
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(priceKeepDot)});

        btTrade.setBackground(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.level_shape_green2 : R.drawable.level_shape_green));
        if (userData != null) {
            btTrade.setText(isBuy ? BuySellEnum.BUY.getTitle() : BuySellEnum.SELL.getTitle());
            ClickUtil.click(btTrade, () -> {
                if (checkParam()) {
                    if (isBuy) {
                        if (isMarketPrice) {
                            orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
                        } else {
                            orderPrice = etPrice.getText().toString();
                        }
                    } else {
                        if (isMarketPrice) {
                            orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
                        } else {
                            orderPrice = etPrice.getText().toString();
                        }
                    }
                    orderPrice = NumberUtil.keepMax(orderPrice, numUSTDKeepDot);

                    TipLevelUtil.showConfirmOrder(getActivity(), isBuy ? getString(R.string.levelCurrentHolderFragment12) : getString(R.string.levelCurrentHolderFragment13), isMarketPrice ? getString(R.string.levelCurrentHolderFragment2) : getString(R.string.levelCurrentHolderFragment3),
                            isMarketPrice ? tvPrice.getText().toString() : etPrice.getText().toString(), etNum.getText().toString(), tvTradeMoney.getText().toString(), (level.intValue()) + "", new TipLevelUtil.OnTipSure() {
                                @Override
                                public void onSure() {
                                    mPresenter.createOrder(etNum.getText().toString(),
                                            orderPrice,
//                                    tvPrice.getText().toString(),
                                            code,
                                            isMarketPrice ? "2" : "1",
                                            isBuy ? "1" : "2",
                                            level + "");
                                }
                            });
                }
            });
        } else {
            btTrade.setText(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment23));
            ClickUtil.click(btTrade, () -> {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);

            });
        }
        changeShowData();
        initRadioGroup();
    }

    /**
     * 先判断是否选择过了仓位，没选择仓位时不进行计算
     * 改变杠杆后，重新更具杠杆进行最大值计算，然后再乘以当前选择的仓位
     */
    private void calculateNumByLecver() {
        if (isSetPositions) {
            calculateMaxTrade();
            String num = new BigDecimal(maxTradeCoin).multiply(new BigDecimal(pager)).multiply(new BigDecimal("0.01")).toBigInteger() + "";
            etNum.setText(num);
        }
    }

    /**
     * 计算最大可输入数量
     */
    private void calculateMaxTrade() {
        if (data == null || TextUtils.isEmpty(currentPrice) || Double.valueOf(currentPrice) == 0 || TextUtils.isEmpty(marketPrice) || Double.valueOf(marketPrice) == 0) {
            maxTradeCoin = "0";
        } else {

            if (isBuy) {
                if (isMarketPrice) {
                    maxTradeCoin = data.getRight_code() + "";
                } else {
                    maxTradeCoin = data.getRight_code() / Double.valueOf(currentPrice).doubleValue() + "";
                }
            } else {
                maxTradeCoin = data.getLeft_code() + "";
            }

//            if (isMarketPrice) {
//                maxTradeCoin = new BigDecimal(usdtMoney).divide(new BigDecimal("1").divide(new BigDecimal(level), 8, BigDecimal.ROUND_HALF_DOWN).add(new BigDecimal(fee)).multiply(new BigDecimal(marketPrice)), 8, BigDecimal.ROUND_HALF_UP).intValue() + "";
//            } else {
//                maxTradeCoin = new BigDecimal(usdtMoney).divide(new BigDecimal("1").divide(new BigDecimal(level), 8, BigDecimal.ROUND_HALF_DOWN).add(new BigDecimal(fee)).multiply(new BigDecimal(currentPrice)), 8, BigDecimal.ROUND_HALF_UP).intValue() + "";
//            }
//            maxTradeCoin = new BigDecimal(maxTradeCoin).divide(new BigDecimal(paperValue), 0, BigDecimal.ROUND_DOWN).toBigInteger() + "";
        }
    }

    /**
     * 检测购买条件
     *
     * @return
     */
    private boolean checkParam() {
        if (userData == null) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment67));
            return false;
        }
        //初级认证

        if (userData.getAuthentication() > 0) {//已实名认证

        } else {
            TipUtil.OnTipSure onTipSure = () ->
                    //跳转身份认证界面
                    ARouter.getInstance().build(RConfig.MINE_VERIFY_HOME).navigation();
        }

        if (isMarketPrice) {
            if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment68));
                return false;
            }
        } else {
            if (TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment69));
                return false;
            }
            if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelJavaBuyAndSellFragment68));
                return false;
            }
        }
//        if (Double.valueOf(etNum.getText().toString()) < Double.valueOf(minTradeCoin)) {
//            ToastUtil.showShort(String.format("", minTradeCoin));
//            return false;
//        }
        return true;
    }

    /**
     * 根据
     * 价格，数量，滑竿更新交易额
     * 价格*数量*（1+手续费）/杠杆
     */
    private void changeShowData() {
        if (TextUtils.isEmpty(etPrice.getText()) || TextUtils.isEmpty(etNum.getText())) {
            tvTradeMoney.setText("0.0000");
        } else {
            String orderPrice = etPrice.getText().toString();
            String usdtFull = "0";
            BigDecimal numBig = new BigDecimal(etNum.getText().toString()).multiply(new BigDecimal(paperValue));

            if (!TextUtils.isEmpty(etNum.getText())) {
                //计算交易额
                if (isBuy) {
                    if (isMarketPrice) {
                        orderPrice = new BigDecimal(marketPrice).add(new BigDecimal(distancePrice)).toPlainString();
                    }
                    usdtFull = new BigDecimal(orderPrice).multiply(numBig).divide(new BigDecimal(level), 8, RoundingMode.HALF_UP).toPlainString();
                } else {
                    if (isMarketPrice) {
                        orderPrice = new BigDecimal(marketPrice).add(new BigDecimal("-" + distancePrice)).toPlainString();
                    }

                    usdtFull = new BigDecimal(orderPrice).multiply(numBig).divide(new BigDecimal(level), 8, RoundingMode.HALF_UP).toPlainString();

                }
                BigDecimal feeBig = new BigDecimal(orderPrice).multiply(numBig).multiply(new BigDecimal(fee));
                usdtFull = new BigDecimal(usdtFull).add(feeBig).toPlainString();
                String usdt;
                usdt = NumberUtil.keep(usdtFull, numUSTDKeepDot);
                tvTradeMoney.setText(usdt);
            } else {
                tvTradeMoney.setText("0.0000");

            }
        }
    }

    public void buySuccess() {
        RxBus.getDefault().send(RxBusCode.LEVEL_FRESH);
        //    ARouter.getInstance().build(RConfig.LEVEL_TRADE).navigation();
    }

    public void updateDeep(WSFiveBean data) {
        Collections.reverse(data.getAsks());
        Collections.reverse(data.getBids());
        Flowable<List<DepthData>> buyFlow = Flowable.fromIterable(data.getBids())
                .map(fiveBean -> new DepthData(Float.valueOf(fiveBean.getTotalSize()), Float.valueOf(fiveBean.getPrice())))
                .toList()
                .toFlowable();
        Flowable<List<DepthData>> sellFlow = Flowable.fromIterable(data.getAsks())
                .map(fiveBean -> new DepthData(Float.valueOf(fiveBean.getTotalSize()), Float.valueOf(fiveBean.getPrice())))
                .toList()
                .toFlowable();

        Flowable.zip(buyFlow, sellFlow, (buyData, sellData) -> {
            if (depthMapView != null) {
                depthMapView.setData(buyData, sellData);
            }
            return "1";
        }).subscribe();
    }

    AssetDetailBean data;

    /**
     * 获取可用usdt
     */
    public void updateUSDT(AssetDetailBean data) {
        this.data = data;
        updateUI();
    }

    public void updateUSDT() {
        if (data == null) {
            return;
        }
        if (isBuy) {
            usdtMoney = mFormat.format(data.getRight_code()) + "";
        } else {
            usdtMoney = mFormat.format(data.getLeft_code()) + "";
        }
        if (!TextUtils.isEmpty(usdtMoney)) {
            if (isBuy) {
                tvMoney.setText(usdtMoney + codeRight);
            } else {
                tvMoney.setText(usdtMoney + type);
            }

        }
    }


    /**
     * 汇率内容
     */
    public void updateHuiLvContent(HuilvContentBean bean) {
        if (bean != null) {
            huilvContent = bean.getUSDT();
        }
    }

    /**
     * 获取惠率
     *
     * @param user
     */
    public void updateStatus(UserInfo user) {
        int lev = 0;
        String rate = "0%";
        if (user.getWallone_usdt() >= user.getMoney1()) {
            lev = 1;
            rate = user.getFree_fee1() + "%";
        }
        if (user.getWallone_usdt() >= user.getMoney2()) {
            lev = 2;
            rate = user.getFree_fee2() + "%";
        }
        if (user.getWallone_usdt() >= user.getMoney3()) {
            lev = 3;
            rate = user.getFree_fee3() + "%";
        }
        if (user.getWallone_usdt() >= user.getMoney4()) {
            lev = 4;
            rate = user.getFree_fee4() + "%";
        }
        if (user.getWallone_usdt() >= user.getMoney5()) {
            lev = 5;
            rate = user.getFree_fee5() + "%";
        }
        tvPreferRate.setText(App.INSTANCE.getString(R.string.level_prefer_rate) + rate);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, code = RxBusCode.VERIFY)
    public void updataVerify() {
        if (userViewModel != null) {
            userViewModel.update();
        }
    }


}
